package com.yuwei.live

import android.os.Handler
import android.os.Looper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.tencent.smtt.utils.l
import com.yuwei.base.RoutePath
import com.yuwei.common.mvi.BaseMviFragment
import com.yuwei.common.mvi.UiState
import com.yuwei.live.adapter.LiveAdapter
import com.yuwei.live.cache.LiveItemCache
import com.yuwei.live.databinding.FragmentLiveBinding
import com.yuwei.live.entity.LiveEntity


@Route(path = RoutePath.LIVE_FRAGMENT)
class LiveFragment : BaseMviFragment<FragmentLiveBinding,LiveViewModel>() {
    private val liveAdapter = LiveAdapter()
    private var mPosition = 0
    override fun successData(it: UiState.onSuccess<*>) {
        when(it.type){
            "getLiveList" -> {
                val liveEntity = it.data as LiveEntity
                LogUtils.d("${liveEntity.size}")
                liveAdapter.data.addAll(liveEntity)
                liveAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun failureData(error: String) {
    }

    override fun initView() {
        vm.sendIntent(LiveIntent.getLiveList(2,20))
        binding.liveRv.adapter = liveAdapter
        val manager = LinearLayoutManager(requireContext())
        binding.liveRv.layoutManager = manager
        val helper = PagerSnapHelper()
        helper.attachToRecyclerView(binding.liveRv)
        liveAdapter.addChildClickViewIds(R.id.go_live)
        //跳转直播间详情
        liveAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.go_live->{
                    ARouter.getInstance().build(RoutePath.LIVE_DETAIL_ACTIVITY).withSerializable("video",liveAdapter.getItem(position)).navigation()
                }
            }
        }
        binding.liveRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if(newState == RecyclerView.SCROLL_STATE_DRAGGING){
                    liveAdapter.shop()
                }else if(newState == RecyclerView.SCROLL_STATE_SETTLING){
                    liveAdapter.start()
                }
            }
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val firstVisiblePosition = manager.findFirstVisibleItemPosition()
                val lastVisiblePosition = manager.findLastVisibleItemPosition()

                // 设置当前播放位置（通常是第一个完全可见的item）
                liveAdapter.setCurrentPosition(firstVisiblePosition)

                // 预加载下一个视频（提前2个位置）
                if (lastVisiblePosition + 2 < liveAdapter.itemCount) {
                    liveAdapter.preloadNext(lastVisiblePosition + 1)
                }
            }
        })
        binding.liveRv.run {
            itemAnimator = null
            setItemViewCacheSize(15)//设置屏幕外的缓存数量，默认为2
            setHasFixedSize(true) //减少固定大小的组件反复测量
            setRecycledViewPool(RecyclerView.RecycledViewPool().apply {
                setMaxRecycledViews(0, 10) //根据不同的组件类型缓存
            })
            setViewCacheExtension(LiveItemCache())
            //滚动时停止图片加载
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        Glide.with(this@LiveFragment).resumeRequests()
                    }
                    if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                        Glide.with(this@LiveFragment).pauseRequests()
                    }
                }
            })
        }
    }

    override fun onPause() {
        super.onPause()
        liveAdapter.release()
    }
    override fun onResume() {
        super.onResume()
        liveAdapter.start()
        liveAdapter.setResume(true)
        liveAdapter.notifyDataSetChanged()
    }
    override fun initData() {

    }

    override fun onDestroy() {
        super.onDestroy()
    }

}